function login(){
    if ($('#login').length) {
        $('.layer').show();
        $('#login').show();
    } else {
        alert("您的登录已失效，请重新登录");
        window.location.reload();
    }
}
function openLogin(type){ 
    if( $("input[name='userdeal']").is(':checked') == false ){
        alert('请勾选用户协议哦!');
        return false;
    }
    var iWidth = 800;
    var iHeight = 600;
    var iTop = (window.screen.availHeight - 30 - iHeight) / 2;
    var iLeft = (window.screen.availWidth - 10 - iWidth) / 2;
    window.open("/login/" + type,"","width="+iWidth+", height="+iHeight+", top="+iTop+", left="+iLeft); 
}
function popup(code, msg){
    if(code==1){
        login();
        return false;
    }
    if(code==2||code==3){
        $('.endfree .pop-msg').text(msg);
        $('.layer').show();
        $('.endfree').show();
        return false;
    }
    if(code==4){
        $('.upbox .pop-msg').text(msg);
        $('.layer').show();
        $('.upbox').show();
        return false;
    }

    if(code==5){
        alert(msg);
        return false;
    }

    if(code==6){
        $('#captcha-img').attr('src', $('#captcha-img').attr('data-src')+'?'+new Date().getTime());
        $('.captcha').show();
        $('.layer').show();
    }

    if(code==7){
        $('#captcha-img').attr('src', $('#captcha-img').attr('data-src')+'?'+new Date().getTime());
        $('.captcha .code-refresh').html(msg).css('color','red');
        $('.captcha').show();
        $('.layer').show();
    }
}

$(function(){
    /* waterfall */
    if ($('.grid-v').length) {
        // alert($('.grid-v').length);
        $('.ones').masonry({
            itemSelector: '.grid-v',
            columnWidth: 288,
            transitionDuration: '0.2s',
            gutter: 14
        });
    }
    if ($('.grid-h').length) {
        $('.ones').flexImages({
            rowHeight: 300,
            container:'.grid-h',
            truncate:true
        });
    }

    /* sign in/up */
    $('.loginin').on('click', function(){
        var name = $(this).attr('name');
        $('.loginname_qq').html('QQ'+name);
        $('.loginname_wx').html('微信'+name);
        login();
    });

    /* common close method */
    $('.aclose').click(function(){
        $(this).parent().hide();
        $('.layer').hide();
    });
    
    /* sidebar */
    $(".returntop").click(function(){
        $("html,body").animate({scrollTop:0}, 300);
    }); 

    /* search */
    function search(){
        var input = 'keyword' == $(this).attr('name') ? $(this) : $(this).parent().find(':input[name="keyword"]');
        var q = $.trim(input.val()),t = $(this).attr('key-type');
        if(q == ''){
            alert('请输入关键词');
            return false;
        }
        $.getJSON("/api/keyword/check", {q:q,t:t}, function(r) {
            if(r.code == 1){
                alert(r.msg);
                return false;
            }
            window.location.href=r.redirect_url;
        });
    }
    $('.search-btn').on('click', search);

    $('.searchtype').on('click',function(){
         var classname = $(this).attr('name');
         var bordername = $(this).attr('border');
         var word = '找'+$(this).html();
         var t = $(this).attr('key-type');
         $(this).addClass(classname).addClass('on').siblings().removeClass('on').removeClass('ybc').removeClass('abc').removeClass('gbc');
         $('.mt .cz').removeClass('ybd').removeClass('gbd').removeClass('abd').addClass(bordername);
         $('.search-btn').removeClass('ybc').removeClass('gbc').removeClass('abc').addClass(classname).html(word).attr('key-type', t);
         $('#dropdown-box').removeClass('ybd').removeClass('gbd').removeClass('abd').addClass(bordername);
         $('#keyword').attr('key-type', t);

         var q = $('#keyword').val();
         if(q != ''){
                $.getJSON("/api/keyword/check", {q:q,t:t}, function(r) {
                if(r.code == 1){
                    alert(r.msg);
                    return false;
                }
                window.location.href=r.redirect_url;
            });
         }
    });

    $('#dropdown-box').on('mousedown', '.tips-item', function(){
        var k = $('#keyword');
        k.val($(this).find('.tips-keyword').text());
        search.call(k);
    });
    $('#dropdown-box-float').on('mousedown', '.tips-item', function(){
        var k = $('#keyword-float');
        k.val($(this).find('.tips-keyword').text());
        search.call(k);
    });

    function renderTips(d){
        c = d.list.length;
        if (c == 0) {
            this.html('').hide();
            return false;
        }
        var h = '<ul class="sotips tips-count" data-length="'+c+'" data-index="'+(c+1)+'">';
        $.each(d.list, function(i, j){
            h += '<li class="tips-item"><a class="tips-keyword';
            if (d.rank && (i + 1) <= 3) {
                h += ' chosefont';
            }
            h += '" herf="javascript:;">' + j + '</a></li>';
        });
        h += '</ul>';
        this.html(h).show();
    }
    $.fn.sotips = function(opts){
        var opts = $.extend({}, {
            box: $('#dropdown-box'),
            isStore: true,
            salt: 'v1'
        }, opts),checkTips = function(){
            var q = $.trim(this.val()),t;
            t = this.attr('key-type');
            f = q+'#'+t+opts.salt;
            var d = store.get(f),n = new Date().getTime() / 1000;
            if (!opts.isStore || "undefined" == typeof(d) || d.expire < n) {
                $.getJSON("/api/search_tips", {q:q,t:t}, function(r) {
                    if(r.code == 1){
                        opts.box.html('').hide();
                    } else {
                        renderTips.call(opts.box, r.data);
                    }
                    store.set(f, r.data);
                });
            } else if (d.list != '') {
                renderTips.call(opts.box, d);
            }
        }
        this.on('focus', function(){
            checkTips.call($(this));
        });
        this.on('blur', function(){
            opts.box.hide();
        });
        this.on('keydown', function(e){
            if (13 == e.which) {
                search.call(this);
                return false;
            }
        });
        this.on('keyup', function(e){
            var k = e.which;
            if (38 == k || 40 == k){
                var c = opts.box.find('.tips-count'),l,i,o;
                l = parseInt(c.attr('data-length'));
                i = parseInt(c.attr('data-index'));
                if (38 == k) {
                    i = i == 0 ? l - 1 : i - 1;
                } else {
                    i = i >= l ? 0 : i + 1;
                }
                c.attr('data-index', i);
                o = opts.box.find('.tips-item').eq(i);
                o.addClass('xiala-hover').siblings().removeClass('xiala-hover');
                $(this).val(o.find('.tips-keyword').text());
            } else {
                checkTips.call($(this));
            }
        });
    };
    
    $('#keyword').sotips();
    $('#keyword-float').sotips({box: $('#dropdown-box-float')});

    // favorite
    $('.ones .collect,.t-bj .collect,.num .collect').on('click', function(){
        if(!isLogin) {
            login();
            return false;
        }
        var type = 0;
        var id = $(this).attr('data-id');
        if($(this).hasClass('chose')){
            type = 1;
            $(this).removeClass('chose');
        } else {
            $(this).addClass('chose');
        }
        var that = $(this);
        $.ajax({
            type: 'get',
            url: '/api/favorite',
            data: {id:id,type:type},
            success: function(res){     
                 if (1 == res.code) {
                    login();
                    that.removeClass('chose');
                 }
            }
        });
    });

    $(document).on('click', '.click-down,#code_submit', function(){
        var id = $(this).attr('data-id');
        var type = $(this).attr('src-type');
        var code = '';
        if ($(this).hasClass('code-submit')) {
            code = $('.code-input').val();
            if ('' == code) {
                alert('请输入验证码');
                return false;
            }
            $('.captcha').hide();
            $('.layer').hide();
        }
        $.ajax({
            type: 'get',
            url: '/api/download',
            data: {id:id,type:type,code:code},
            success: function(res){     
                if (0 == res.code) {
                    window.location.href = res.url;
                } else {
                    if (6 == res.code) {
                        $('#code_submit').attr('data-id', id);
                    }
                    popup(res.code, res.msg);
                }
            }
        });
    });

    $('.captcha').on('click', '.code-refresh', function(){
        $('#captcha-img').attr('src', $('#captcha-img').attr('data-src')+'?'+new Date().getTime());
    });

    // sidebar
    $('.rightbar .qq-ctn').hover(function(){
        $('.float-qq').show();
    }, function(){
        $('.float-qq').hide();
    });

    // 
    $('.float-qq-btn2').on('click', function(){
        if(!isLogin) {
            login();
            return false;
        }
        $('.uplcheck').show();
        $('.layer').show();
    });
});

$(window).load(function() {
    /* lazyload */
    $("img.lazy").lazyload({
        effect: "show",
        threshold : 300,
        failurelimit:10
    });
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?46d35eea42545bae7bbea2d951fc4dd8";
      var s = document.getElementsByTagName("script")[0]; 
      s.parentNode.insertBefore(hm, s);
    })();
    if (is_push) {
        (function(){
            var bp = document.createElement('script');
            var curProtocol = window.location.protocol.split(':')[0];
            if (curProtocol === 'https') {
                bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
            }
            else {
                bp.src = 'http://push.zhanzhang.baidu.com/push.js';
            }
            var s = document.getElementsByTagName("script")[0];
            s.parentNode.insertBefore(bp, s);
        })();
    }
});